package com.issc.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;



public class LoginTest {
	
	
	public static void main(String[] args) {
		//statement sql注入
		try {
			login_state("zhangsan' or ' 1=1","1234");
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
		//使用preparedstatement预编译，不会产生sql注入
		try {
			login_prepa("zhangsan' or ' 1=1","1234");
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void login_state(String username,String password) throws ClassNotFoundException, SQLException{
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://localhost:3306/homework?useUnicode=true&amp;characterEncoding=utf-8";
		Connection conn=DriverManager.getConnection(url,"root","root123");
		Statement sm = conn.createStatement();
		String sql = " select * from user where " + " uname='" + username + "' and upassword='" + password + "'";
		ResultSet re = sm.executeQuery(sql);
		if(re.next()){
			System.out.println("恭喜 " + username + "登录成功");
			System.out.println(sql);
		}else{
			System.out.println("登录失败，账号或密码错误");
		}
		re.close();
		sm.close();
		conn.close();
		
	}
	
	public static void login_prepa(String username,String password) throws ClassNotFoundException, SQLException{
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://localhost:3306/homework?useUnicode=true&amp;characterEncoding=utf-8";
		Connection conn=DriverManager.getConnection(url,"root","root123");
		String sql = "select * from user where uname=? and upassword=?";
		PreparedStatement psm = conn.prepareStatement(sql);
		psm.setString(1,username);
		psm.setString(2,password);
		ResultSet re = psm.executeQuery();
		if(re.next()){
			System.out.println("恭喜 " + username + "登录成功");
			System.out.println(sql);
		}else{
			System.out.println("登录失败，账号或密码错误");
		}
		re.close();
		psm.close();
		conn.close();
		
	}

}
